package com.xcm.util;

import com.google.common.collect.Maps;
import com.xcm.config.CustomProperties;
import com.xcm.constant.FileConstant;
import com.xcm.model.dto.BottomProgramDTO;
import com.xcm.model.dto.TopProgramDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

/**
 * 校验节目是否合法
 */
public class ValidateProgramJsonUtils {

	private static Logger logger = LoggerFactory.getLogger(ValidateProgramJsonUtils.class);

	/**
	 * 校验节目
	 * @param xcVersion xc版本
	 * @param topList 上屏节目列表
	 * @param bottomList 下屏节目列表
	 * @param fileDownloadTempStoreDir 文件下载临时存放目录
	 * @return  Map<String, Integer>
	 */
	public static Map<String, Integer> validateProgram(String xcVersion, List<TopProgramDTO> topList, List<BottomProgramDTO> bottomList, String fileDownloadTempStoreDir) {
		//创建文件临时存储目录
		if (StringUtils.isBlank(fileDownloadTempStoreDir)) {
			throw new NullPointerException("fileDownloadTempStoreDir参数不能为空");
		}
		//文件不存在列表、不合法视频文件（时长差的绝对值大于1）
		Map<String, Integer> illegalMsgMap = Maps.newHashMap();
		//系统分隔符
		String separator = File.separator;
		if (fileDownloadTempStoreDir.endsWith(separator)) {
			fileDownloadTempStoreDir = fileDownloadTempStoreDir + xcVersion + separator;
		} else {
			fileDownloadTempStoreDir = fileDownloadTempStoreDir + separator + xcVersion + separator;
		}
		File storeFileDir = new File(fileDownloadTempStoreDir);
		if (!storeFileDir.exists()) {
			storeFileDir.mkdirs();
		}
		// TODO: 2018/5/16  下载上屏文件 目前规定所有上屏文件都是avi格式的视频文件，如果以后有改动，请修改此处
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < topList.size(); i++) {
			TopProgramDTO topDTO = topList.get(i);
			String name = topDTO.getName();
			if (StringUtils.isBlank(name)) {
				continue;
			}
			//文件存储全路径
			sb.append(fileDownloadTempStoreDir).append(name).append(FileConstant.VIDEO_SUFFIX_AVI);
			String url = topDTO.getUrl();
			if (StringUtils.isNotBlank(url)) {
				//验证名称是否与URL中的名称一样
				int videoNameIndexBegin = url.lastIndexOf("/") + 1;
				String substring = url.substring(videoNameIndexBegin, url.length());
				String videoName = substring.replace(FileConstant.VIDEO_SUFFIX_AVI, "");
				//名称相同就下载
				if (name.equals(videoName)) {
					try {
						FileUtils.downloadFileFromURL(url, sb.toString());
					} catch (IOException e) {
						e.printStackTrace();
						logger.error(name + FileConstant.VIDEO_SUFFIX_AVI + "不存在");
					}
				}
			}
			sb.setLength(0);
		}
		//初始化sb长度为0
		// TODO: 2018/5/16  下载下屏文件 目前规定所有上下文件都是jpg格式的图片文件，如果以后有改动，请修改此处
		sb.setLength(0);
		//下载下屏文件
		for (int i = 0; i < bottomList.size(); i++) {
			BottomProgramDTO bottomDTO = bottomList.get(i);
			String name = bottomDTO.getName();
			if (StringUtils.isBlank(name)) {
				illegalMsgMap.put("图片文件名为空", FileConstant.FILE_NAME_IS_NULL);
				continue;
			}
			sb.append(fileDownloadTempStoreDir).append(name).append(FileConstant.PICTURE_SUFFIX_JPG);
			String url = bottomDTO.getUrl();
			if (StringUtils.isNotBlank(url)) {
				//验证名称是否与URL中的名称一样
				int videoNameIndexBegin = url.lastIndexOf("/") + 1;
				String substring = url.substring(videoNameIndexBegin, url.length());
				String pictureName = substring.replace(FileConstant.PICTURE_SUFFIX_JPG, "");
				if (name.equals(pictureName)) {
					try {
						FileUtils.downloadFileFromURL(url,sb.toString());
					} catch (IOException e) {
						//如果文件不存在，添加到返回信息
						illegalMsgMap.put(name + FileConstant.PICTURE_SUFFIX_JPG, FileConstant.FILE_NOT_FOUND);
						e.printStackTrace();
						logger.error(name + FileConstant.PICTURE_SUFFIX_JPG + "不存在");
					}
				} else {
					illegalMsgMap.put(name + FileConstant.PICTURE_SUFFIX_JPG, FileConstant.FILE_NOT_FOUND);
				}
			} else {
				illegalMsgMap.put(name, FileConstant.FILE_URL_IS_NULL);
			}
			sb.setLength(0);
		}
		//初始化sb长度为0
		sb.setLength(0);
		//校验视频文件（校验视频文件是否存在和视频时长）
		for (int i = 0; i < topList.size(); i++) {
			TopProgramDTO topDTO = topList.get(i);
			String name = topDTO.getName();
			if (StringUtils.isBlank(name)) {
				illegalMsgMap.put("视频文件名为空", FileConstant.FILE_NAME_IS_NULL);
				continue;
			}
			Integer duration = topDTO.getDuration();
			if (duration == null) {
				illegalMsgMap.put(name, FileConstant.VIDEO_DURATION_IS_NULL);
				continue;
			}
			sb.append(fileDownloadTempStoreDir).append(name).append(FileConstant.VIDEO_SUFFIX_AVI);
			File file = new File(sb.toString());
			if (file.exists()) {
				// DSP传过来的值是精确到秒的，自己组装的数据是毫秒值
				if (duration > 1000) {
					Long longVideoDuration = MultimediaUtils.readVideoLongDuration(file);
					long diffAbs = Math.abs(duration - longVideoDuration);
					//获取小数位
					DecimalFormat df = new DecimalFormat("0.00");
					String format = df.format(diffAbs);
					double diff = Double.parseDouble(format);
					//如果时长差大于1，校验不通过
					if (diff > 1) {
						illegalMsgMap.put(name + FileConstant.VIDEO_SUFFIX_AVI, FileConstant.VIDEO_DURATION_ILLEGAL);
					}
				} else {
					//读取视频时长
					double videoDuration = MultimediaUtils.readVideoDuration(file);
					//视频时长差（用读取到的视频时长减去原始视频时长）
					double diff = videoDuration - Double.parseDouble(String.valueOf(duration));
					//如果时长差大于1，校验不通过
					DecimalFormat df = new DecimalFormat("0.00");
					String format = df.format(diff);
					double formatDouble = Double.parseDouble(format);
					if (Math.abs(formatDouble) > 1) {
						illegalMsgMap.put(name + FileConstant.VIDEO_SUFFIX_AVI, FileConstant.VIDEO_DURATION_ILLEGAL);
					}
				}
			} else {
				illegalMsgMap.put(name + FileConstant.VIDEO_SUFFIX_AVI, FileConstant.FILE_NOT_FOUND);
			}
			sb.setLength(0);
		}
		return illegalMsgMap;
	}
}
